/**
 * 
 */
package net.kaizhong.j2ee01.websocket;

import java.io.IOException;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @author kzuser
 *
 */

@ServerEndpoint("/echo/hello")
public class EchoWebSocket
{
    private static final Logger logger = LogManager.getLogger(EchoWebSocket.class);

    public EchoWebSocket()
    {
        logger.info("开始执行构造函数 EchoWebSocket()");
        logger.info("结束执行构造函数 EchoWebSocket()");
    }

    @OnOpen
    public void onOpen(Session session)
    {
        logger.info("开始建立链接 EchoWebSocket.onOpen()");
        logger.info("结束建立链接 EchoWebSocket.onOpen()");
    }

    @OnMessage
    public void sayHello(Session session, String msg)
    {
        logger.info("开始执行消息处理方法 EchoWebSocket.sayHello()");

        try
        {
            if (session.isOpen())
            {
                session.getBasicRemote().sendText(msg);
            }
        }
        catch (IOException e)
        {
            try
            {
                session.close();
            }
            catch (IOException e1)
            {

            }
        }
        logger.info("结束执行消息处理方法 EchoWebSocket.sayHello()");
    }

    @OnMessage
    public void echoPongMessage(PongMessage pm)
    {

    }

    @OnClose
    public void onClose(Session session, CloseReason reason)
    {
        logger.info("开始关闭链接 EchoWebSocket.onClose()");
        logger.info("结束关闭链接 EchoWebSocket.onClose()");
    }

    @OnError
    public void onError(Session session, Throwable error)
    {
        logger.info("开始异常处理 EchoWebSocket.onError()");
        logger.info("结束异常处理 EchoWebSocket.onError()");
    }
}
